//
//  FreedomPlayerController.swift
//  Gamers
//
//  Created by 虚空之翼 on 15/10/2.
//  Copyright © 2015年 Freedom. All rights reserved.
//

import UIKit
import youtube_ios_player_helper

class FreedomPlayerController: UIViewController {
    
    var videoData: YTVideo!

    @IBOutlet weak var playerView: YTPlayerView!
    @IBOutlet weak var descriptionView: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(),forBarMetrics: UIBarMetrics.Default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        self.navigationController?.navigationBar.translucent = true
        // 播放设置
        playerView.delegate = self
        let playerVars = ["playsinline": 1, "showinfo": 1]
        playerView.loadWithVideoId(videoData.id, playerVars: playerVars)
        // 内容介绍
        descriptionView.text = videoData.videoDescription
        //print(videoData)
        // 播放全屏的监听事件
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "endFullScreen", name: UIWindowDidBecomeHiddenNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "begainFullScreen", name: UIWindowDidBecomeVisibleNotification, object: nil)

    }
    // 隐藏系统状态栏
    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return UIStatusBarStyle.Default
    }
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // 横屏切换
    func begainFullScreen() {
        let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        appDelegate.allowRotation = true
        
    }
    
    func endFullScreen() {
        let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        appDelegate.allowRotation = false
        
        //强制归正：
        let sharedApplication: UIApplication = UIApplication.sharedApplication()
        sharedApplication.setStatusBarOrientation(UIInterfaceOrientation.Portrait, animated: true)
        let mvc: UIViewController = UIViewController()
        self.presentViewController(mvc, animated: true, completion: nil)
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }

}

// MARK: - youtube播放代理
extension FreedomPlayerController: YTPlayerViewDelegate {
    // 加载完成立即播放
    func playerViewDidBecomeReady(playerView: YTPlayerView!) {
        playerView.playVideo()
    }
}
